use strict;
use warnings;

use JSON;
use IO::Socket;

my $socket;
my $client_name = 'odch';

sub main {
	my $i = 0;
	while (not $socket) {
		print "attempting to establish internal comms\n";
		$socket = IO::Socket::INET->new('localhost:9003');
		if ($socket) {
			print "connected!\n";
			my $message = encode_json({ type => 'register_incoming', name => $client_name}) . "\n";
			print "MESSAGE: $message";
			print $socket $message;
			last;
		}

		if (++$i > 10) {
			print "tried ten times, giving up";
			exit;
		}
		sleep 5;
	}

	map { proxy($_) } qw(
		data_arrival
		op_admin_connected
		op_connected
		reg_user_connected
		new_user_connected
		user_disconnected
		hub_timer
		added_perm_ban
		added_temp_ban
		added_perm_allow
	);
}

sub proxy {
	no strict 'refs';
	my $method = shift;
	*{"::$method"} = sub {
		my $encoded = encode_json({type => function => details => [$method, [@_]]});
		print $socket "$encoded\n";
		print "SENDING: $encoded\n";
	};
}
